/**
 * @description 登录
 */

import style from './styles/App.less';
import classnames from "classnames";
import React from 'react';
import axios from 'axios';
import config from "commons/config";
import EntryBase from "../Common/EntryBase";
const Fragment = React.Fragment;
import { Button, Picker, Icon, InputItem, List, Toast, Popup } from 'wd-mobile';

import TimmerBtn from "components/TimmerBtn";
import { registerOrlogin, sendMobileCode, loginByToken, regGiftConf } from "api_xukaiyu/app/login";

import img_logo from "images/logo.png";

import util from "commons/util";

const queryObject = util.parseQueryString();

let prizeType = {
    0: '元',
    1: '折'
}
class App extends EntryBase {
    constructor(props) {
        super(props);
        this.state = {
            formData: {
                mobile: "",
                mobileCode: "",
                appType: "H5",
                token: ""
            },
            seconds: 3,
            newAward: [],
            visible: false,
            isFlagState: !!(+queryObject.flag), // 是否可切换登录类型
            isOld: !!(+queryObject.flag)// 新老用户 非0为老用户
        }
    }
    componentDidMount() {
        if (!!util.isWeixin() || !!config.wechat.notAllowdOutOfWechat) {
            this.wxAuthorize().then(res => {
                this.setState(res);
            });
        }

        // regGiftConf().then(data => {
        //     this.setState({
        //         visible: true,
        //         newAward: data.data
        //     }, () => {

        //     })
        // })
    }
    render() {
        let { visible, newAward, seconds } = this.state;
        return (
            <Fragment>
                <div className={classnames(style.main)}>
                    <div className={style.backHome} onClick={() => {
                        location.href = "./index.html";
                    }}>返回首页</div>
                    <div className={style.logo}><img src={img_logo} width="200" alt="" /></div>
                    <div className={style.title}>登录/注册出卡拉权益</div>
                    {
                        ((util.isWeixin() && !!this.state.isFlagState && !this.state.isOld) || !(util.isWeixin() && !!this.state.isFlagState)) &&
                        <div className={style.form}>
                            <div className={style.input}>
                                <div className={style.inputLeft}>
                                    <span>手机号</span>
                                    <input type="tel" placeholder="请输入手机号" onChange={(e) => {
                                        this.inputOnChange("mobile", e.target.value)
                                    }} onBlur={this.inputOnBlurFix} />
                                </div>
                            </div>
                            <div className={style.input}>
                                <div className={classnames(style.inputCheckCode, style.inputLeft)}>
                                    <span>验证码</span>
                                    <input type="tel" placeholder="请输入验证码" maxLength={6} onChange={(e) => {
                                        this.inputOnChange("mobileCode", e.target.value)
                                    }} onBlur={this.inputOnBlurFix} />
                                </div>
                                <div>
                                    <TimmerBtn className={style.sendBtn} disabled={!util.isMobile(this.state.formData.mobile)} disabledClick={() => {
                                        if (!this.state.formData.mobile) {
                                            Toast.info("请先输入手机号");
                                            return;
                                        }
                                        if (!util.isMobile(this.state.formData.mobile)) {
                                            Toast.info("请输入正确的手机号")
                                        }
                                        return false;
                                    }} validClick={(callback) => {
                                        this.getMobileCode(callback || function () { });
                                    }} />
                                </div>
                            </div>
                        </div>
                    }
                    <div className={classnames(style.changeBtnContainer)}>
                        {
                            util.isWeixin() && !!this.state.isOld && <Button inline className={style.wxLoginBtn} onClick={() => {
                                this.loginByToken()
                            }}>微信授权登录</Button>
                        }
                        {
                            util.isWeixin() && !this.state.isOld && <Button inline className={style.changeBtn} onClick={() => {
                                this.login()
                            }}>登录并绑定微信</Button>
                        }
                        {
                            !util.isWeixin() && <Button inline className={style.changeBtn} onClick={() => {
                                this.login()
                            }}>登录</Button>
                        }
                        {
                            util.isWeixin() && !!this.state.isFlagState && <div className={style.loginWay} onClick={() => {
                                this.setState({
                                    isOld: !this.state.isOld
                                })
                            }}><span>{!!this.state.isOld ? "使用手机号登录" : "使用微信登录"}</span></div>
                        }
                    </div>
                    <div className={style.agreement}>登录即同意<a href={config.agreement.heyjie_userresgist}>《用户协议》</a></div>
                </div>
                <Popup offset={{ top: '10%', left: 0, right: 0 }} maskStyle={{ 'background': "rgba(0,0,0,.4)" }} mask={true} animation="zoomOut" visible={visible}>
                    <div className={style.redPacket}>
                        <div className={style.title}>新人红包已到账</div>
                        <div className={style.red}>
                            <div className={style.award}>
                                {
                                    newAward.map((item, index) => {
                                        return <div key={index}>
                                            <div onClick={this.redPacketClick} className={style.money}><span hidden={newAward[index].prizeType == 1}>¥</span>{`${util.Mul(parseFloat(newAward[index].denomination), (newAward[index].prizeType == '1' ? 10 : 1))}`}<span hidden={newAward[index].prizeType != 1}>折</span></div>
                                            <div className={style.otherInfo}>
                                                <div className={style.redPacketName}>{item.redPacketName}</div>
                                                <div className={style.endTime}>{util.dateFormat(new Date(item.endTime), 'yyyy.MM.dd')}}到期</div>
                                            </div>
                                        </div>
                                    })
                                }
                            </div>
                            <div className={style.bottom}>
                                <div className={style.tips}>红包卡券可以在“个人中心”“红包”查看</div>
                                <div className={style.seconds}>{seconds}秒后返回商品页</div>
                            </div>
                            <div className={style.close} onClick={this.redPacketClick}></div>
                        </div>
                    </div>
                </Popup>
            </Fragment>
        )
    }

    redPacketClick = () => {
        if (queryObject.redirectUrl) {
            location.replace(queryObject.redirectUrl);
        } else {
            location.replace("./index.html");
        }
    }

    // 微信中键盘退出页面无法回位问题修复
    inputOnBlurFix() {
        setTimeout(function () {
            var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
            window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 100);
    }

    // 输入监听
    inputOnChange(type, value) {
        const formData = { ...this.state.formData };
        formData[type] = value || "";
        this.setState({
            formData: formData
        })
    }

    // 获取手机验证码
    getMobileCode(callback) {
        sendMobileCode({
            mobile: this.state.formData.mobile,
            token: this.wechatToken
        }).then(() => {
            callback && callback();
        })
    }

    // 登录
    login() {
        // 验证数据
        if (!this.state.formData.mobile) {
            Toast.info("请输入手机号");
            return;
        }
        if (!util.isMobile(this.state.formData.mobile)) {
            Toast.info("请输入正确的手机号");
            return;
        }
        if (!this.state.formData.mobileCode) {
            Toast.info("请输入验证码");
            return;
        }

        const inviteUid = sessionStorage.getItem('inviteUid');

        // 登录请求
        registerOrlogin({ referrerUid: inviteUid || '', ...this.state.formData, ...{ token: queryObject.token || this.wechatToken } }).then((res) => {
            sessionStorage.removeItem('inviteUid');
            if (res.data.isNew) {
                regGiftConf().then(data => {
                    this.setState({
                        visible: true,
                        newAward: data.data
                    }, () => {
                        let timer = setInterval(() => {
                            if (this.state.seconds) {
                                this.setState({
                                    seconds: --this.state.seconds
                                })
                            } else {
                                clearInterval(timer);
                                if (queryObject.redirectUrl) {
                                    location.replace(queryObject.redirectUrl);
                                } else {
                                    location.replace("./index.html");
                                }
                            }
                        }, 1000);
                    })
                })
            } else {
                if (queryObject.redirectUrl) {
                    location.replace(queryObject.redirectUrl);
                } else {
                    location.replace("./index.html");
                }
            }

        });
        return false;
    }

    // 微信登录授权
    loginByToken() {
        loginByToken({
            token: queryObject.token || this.wechatToken
        }).then((res) => {
            if (queryObject.redirectUrl) {
                location.replace(queryObject.redirectUrl);
            } else {
                location.replace("./index.html");
            }
        });
    }
}

export default App;